using System;
using Microsoft.SPOT;
using FusionWare.SPOT;
using Microsoft.SPOT.Hardware;
using FusionWare.SPOT.Hardware;

namespace $rootnamespace$
{
    /// <summary>Managed Driver for the emulated Simple I2CDevice</summary>
    /// <remarks>
    /// This demonstrates a managed code driver for an I2C Device. The device
    /// is the emulated <see cref="FusionWare.SPOT.Emulator.SimpleI2CDevice" />.
    /// It has only one 16 bit "Chip ID" register (or command/response if you like).
    /// 
    /// While the device communication and "register set" is simplistic this
    /// sample is a complete driver illustrating best practices for managed drivers.
    /// This includes encapsulating internal details, isolating the device driver from
    /// the bus ther device is on and supporting IDisposable so that GPIO Pin
    /// resources are properly freed by deriving from <see cref="I2CDeviceDriver" />. 
    /// This may seem like an academic excercise, however it is vitally important for
    /// re-usablity of drivers in different systems. It is possible that a system could
    /// share the GPIO Pins for the underlying bus via an external multiplexer. If
    /// proper encapsulation and IDisposable are not used correctly then the driver
    /// would not work on such a system. 
    /// </remarks>
    public partial class $safeitemname$ : I2CDeviceDriver
    {
        const int ClockRateKhz = 25;

        private enum Registers : byte
        {
            ChipID = 0x5A
        }

        /// <summary>Creates a new device instance</summary>
        /// <param name="Address">Address of the bus (including read write bit of 0)</param>
        /// <remarks>
        /// This will create a new device instance of the driver at the specified address.
        /// The address is the same as used by the I2CDevice.Configuration. 
        /// </remarks>
        public $safeitemname$(I2CBus Bus, ushort Address)
            : base(Bus, Address, ClockRateKhz)
        {
        }
	
        /// <summary>Gets the Chip ID</summary>
        /// <value>Chip ID retrieved from the device</value>
        /// <remarks>
        /// This property will cache the ID so that it is actually read from the
        /// device only once. This is a read only register.
        /// </remarks>
        /// <Note>This is just a sample of a possible register. No known real device actually implements this particular functionality</Note>
        public ChipIDReg ChipID
        {
            get
            {
                // 0 is the initial state of the value
                // it is also an invalid ID so use that
                // to check if the data is cached already.
                if(this._ChipID.Value == 0)
                    this._ChipID.Value = base.ReadReg16( (byte)Registers.ChipID, ByteOrder.LittleEndian);

                return this._ChipID;
            }
        }
        private ChipIDReg _ChipID;
    }
}
